﻿/*-------------------------------------
//
//Copyright (C) 2007 开发二组 版权所有。
//
//文件名：CartInfo.cs
//
//
//文件功能描述：生成订单页面，显示生成的订单号.
//
//
//创建标识：2007.11.22 翟丛兴
//创建描述：生成订单的操作
//
//------------------------------------*/
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Net.Mail;

/// <summary>
/// 订单生成页面
/// </summary>
public partial class Common_Controls_FinishOrder : System.Web.UI.UserControl
{

    //保存购物车中的商品列表
    private DataSet dsCartList = new DataSet();
    //保存订单信息的实体
    localhost.OrderInfo orderInfoObj = new localhost.OrderInfo();
    //WebService的DocumentService的对象
    localhost.DocumentService documentServiceObj = new localhost.DocumentService();

    protected delegate bool AsyncSendEmail(string strToEmail, string strOrderInfoID, DateTime date);


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //判断是否已填写送货信息，如果没有填写，转到填写送货信息页面
            if (Session["OrderInfoModel"] == null)
            {
                Response.Write("<script language=javascript> alert('请填写送货信息！');window.location.href='PreviewOrder.aspx'</script>");
                //Response.Redirect("PreviewOrder.aspx");
            }

            //判断是注册顾客还是匿名顾客，根据不同情况生成订单
            if ((Session["CustomerID"] != null) && (Session["CustomerID"].ToString() != "") && (Session["CustomerID"].ToString() != "CUS-00000000"))
            {
                //如果是注册顾客,进行生成订单操作
                //得到注册顾客购物车中商品列表
                localhost.CartService cartServiceObj = new localhost.CartService();
                try
                {
                    dsCartList = cartServiceObj.GetProductList(Session["CustomerID"].ToString());

                    //判断购物车商品列表是否为空
                    if ((dsCartList != null) && (dsCartList.Tables[0].Rows.Count > 0))
                    {
                        //购物车不为空，生成订单
                        CreateOrder();
                        //生成订单后删除购物车中的商品
                        cartServiceObj.DeleteAllProduct(Session["CustomerID"].ToString());
                    }
                    else
                    {
                        Response.Write("<script language=javascript> alert('请先选购商品！');window.location.href='ManageCart.aspx'</script>");
                    }
                }
                catch
                {
                    Response.Write("<script language=javascript> alert('得到购物车中的商品出错!');window.location.href='PreviewOrder.aspx'</script>");
                }
            }
            else if (Session["CartList"] != null)
            {
                //如果是匿名顾客，并且已填写送货信息
                dsCartList = (DataSet)Session["CartList"];

                //判断购物车商品列表是否为空
                if ((dsCartList != null) && (dsCartList.Tables["ProductList"].Rows.Count > 0))
                {
                    //购物中商品不为空，生成订单
                    CreateOrder();
                    //生成订单后删除购物车中的商品
                    Session["CartList"] = null;
                }
                else
                {
                    Response.Write("<script language=javascript> alert('请先选购商品！');window.location.href='ManageCart.aspx'</script>");
                }
            }

        }//End if(!Page.IsPostBack)
    }

    /// <summary>
    /// 生成订单（包括生成订单项，并显示生成订单的订单号）
    /// </summary>
    private void CreateOrder()
    {
        try
        {
            //购物中商品不为空，生成订单
            orderInfoObj = (localhost.OrderInfo)Session["OrderInfoModel"];
            orderInfoObj = documentServiceObj.InsertOrderInfo(orderInfoObj);

            //插入订单项到数据库
            DataTable daCartlist = dsCartList.Tables[0];
            for (int i = 0; i < daCartlist.Rows.Count; i++)
            {
                //得到订单项的信息
                string strOrderInfoID = orderInfoObj.OrderInfoID;
                string strProductID = daCartlist.Rows[i]["ProductID"].ToString();
                int iQuantity = Convert.ToInt32(daCartlist.Rows[i]["Quantity"]);
                decimal decUnitPrice = Convert.ToDecimal(daCartlist.Rows[i]["SalesPrice"]);

                //向数据库中插入订单项
                documentServiceObj.AddOrderItem(strOrderInfoID, strProductID, iQuantity, decUnitPrice);
            }

            //显示生成的订单号和订单生成时间
            lblOrderID.Text = orderInfoObj.OrderInfoID;
            lblTimeNow.Text = orderInfoObj.CreationTime.ToLongDateString();

            //发送邮件到送货人的邮箱中，提示其订单号
            if (Session["ShipEmail"] != null)
            {
                try
                {
                    #region  异步调用WebService发送邮件
                    //localhost.CustomerService customerServiceObj = new localhost.CustomerService();
                    //customerServiceObj.SendEmailCompleted += new localhost.SendEmailCompletedEventHandler(customerServiceObj_SendEmailCompleted);
                    //customerServiceObj.SendEmailAsync(Session["ShipEmail"].ToString(), orderInfoObj.OrderInfoID, orderInfoObj.CreationTime);
                    #endregion

                    //异步调用表示层发送邮件的方法
                    AsyncSendEmail asyncSendEmailObj = new AsyncSendEmail(SendEmail);
                    asyncSendEmailObj.BeginInvoke(Session["ShipEmail"].ToString(), orderInfoObj.OrderInfoID, orderInfoObj.CreationTime, null, this.Page);
                }
                catch
                {
                }

                #region 调用表示层同步发送邮件，已注释
                ////如果发送邮件成功，提示顾客“订单号已发送到您的邮箱”，否则不提示
                //if (SendEmail(Session["ShipEmail"].ToString(), orderInfoObj.OrderInfoID, orderInfoObj.CreationTime))
                //{
                //    lblTip.Visible = true;
                //}
                //else
                //{
                //    lblTip.Visible = false;
                //}
                #endregion
            }


        }
        catch
        {
            Response.Write("<script language=javascript> alert('对不起，你的订单生成失败！!');window.location.href='PreviewOrder.aspx'</script>");
        }
    }

    ///// <summary>
    ///// 异步发送邮件成功后的回调函数
    ///// </summary>
    ///// <param name="sender"></param>
    ///// <param name="e"></param>
    //public void customerServiceObj_SendEmailCompleted(Object sender, localhost.SendEmailCompletedEventArgs e)
    //{
    //    //如果发送邮件成功，提示顾客“订单号已发送到您的邮箱”，否则不提示
    //    if ((e.Error == null) && (!e.Cancelled) && (e.Result))
    //    {
    //        lblTip.Visible = true;
    //    }
    //    else
    //    {
    //        lblTip.Visible = false;
    //    }
    //}

    /// <summary>
    /// 发送生成的订单号到顾客的邮箱中
    /// </summary>
    /// <param name="strToEmail">顾客的邮箱</param>
    /// <param name="strOrderInfoID">订单号</param>
    /// <param name="date">下订单的日期</param>
    /// <returns>发送成功返回true,失败返回false</returns>
    private bool SendEmail(string strToEmail, string strOrderInfoID, DateTime date)
    {
        //配置发送邮件的客户端信息
        SmtpClient smtpClientObj = new SmtpClient("smtp.sina.com");
        smtpClientObj.UseDefaultCredentials = false;
        smtpClientObj.Credentials = new System.Net.NetworkCredential("langzizcx@sina.com", "04061131");
        smtpClientObj.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;

        //组织要发送邮件的标题，内容等信息
        MailMessage mailMessageObj = new MailMessage("langzizcx@sina.com", strToEmail);
        mailMessageObj.Subject = "您在SmartBusiness下了订单，这是您的订单号";
        mailMessageObj.Body = "尊敬的顾客，您于 " + date.ToLongDateString() + "在 SmartBusiness 下了订单,您的订单号为：" + strOrderInfoID +
                               "。  您随时可以到网站上查询订单状态，谢谢您的惠顾！";
        mailMessageObj.BodyEncoding = System.Text.Encoding.UTF8;
        mailMessageObj.IsBodyHtml = true;

        try
        {
            //发送邮件
            smtpClientObj.Send(mailMessageObj);
            return true;
        }
        catch
        {
            //发生异常时,返回发送邮件失败
            return false;
        }
    }


    

}
